package message

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"
)

// SendWithJuhe 使用聚合短信发送短信验证码
func SendWithJuhe(tplID, tplValue, tel string) error {
	url := fmt.Sprintf("http://v.juhe.cn/sms/send?key=%s&mobile=%s&tpl_id=%s&tpl_value=%s",
		"86011a372c3576ecd0b45d36877768bb", tel, tplID, tplValue)

	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		return err
	}

	ctx, cancel := context.WithTimeout(context.Background(), time.Second*15)
	defer cancel()
	req = req.WithContext(ctx)

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	var result struct {
		Reason    string `json:"reason"`
		ErrorCode int    `json:"error_code"`
	}
	err = json.NewDecoder(resp.Body).Decode(&result)
	if err != nil {
		return err
	}

	log.Printf("短信验证码响应结果：%v", result)
	if result.ErrorCode != 0 {
		return fmt.Errorf(result.Reason)
	}

	return nil
}

// SendVerifyCode 发送短信验证码
func SendVerifyCode(tel, code string) error {
	tplValue := "%23code%23%3D" + code
	return SendWithJuhe("4931", tplValue, tel)
}

// AsyncSendVerifyCode 异步发送短信验证码
func AsyncSendVerifyCode(tel, code string) {
	go func() {
		err := SendVerifyCode(tel, code)
		if err != nil {
			log.Printf("发送验证码发送错误：%v\n", err)
		}
	}()
}
